package org.feng.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.feng.entity.Dict;
import org.feng.base.entity.Result;
import org.feng.service.DictService;

import lombok.AllArgsConstructor;
import org.feng.utils.ExcelUtils;
import org.feng.utils.TreeUtil;
import org.feng.utils.condition.Condition;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 *
 * </p>
 *
 * @author feng
 * @since 2021-08-27
 */
@RestController
@RequestMapping("/system/dict")
@AllArgsConstructor
public class DictController {

    private final DictService dictService;

    /**
     * 导出
     */
    @GetMapping("/netDict/{code}")
    public Result<List<Dict>> netDict(@PathVariable String code) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("code", code).gt("parent_id", 0);
        return Result.success(dictService.list(wrapper));
    }

    /**
     * 导出
     */
    @GetMapping("/export")
    public void export(HttpServletResponse response) throws IOException {
        ExcelUtils.writeExcel(response, dictService.list(), Dict.class);
    }

    /**
     * 列表
     */
    @GetMapping
    public Result<List<Dict>> list(Dict dict) {
        return Result.success(TreeUtil.tree(dictService.list(Condition.getQueryWrapper(dict))));
    }

    /**
     * 分页列表
     */
    @GetMapping("/page")
    public Result<IPage<Dict>> page(Dict dict) {
        return Result.success(dictService.page(Condition.getPage(), Condition.getQueryWrapper(dict)));
    }

    /**
     * 详情
     */
    @GetMapping("/query")
    public Result<Dict> detail(@RequestParam Long id) {
        return Result.success(dictService.getById(id));
    }

    /**
     * 新增
     */
    @PostMapping
    public Result<Boolean> save(@RequestBody Dict dict) {
        return Result.status(dictService.save(dict));
    }

    /**
     * 修改
     */
    @PutMapping
    public Result<Boolean> update(@RequestBody Dict dict) {
        return Result.status(dictService.updateById(dict));
    }

    /**
     * 删除
     */
    @DeleteMapping
    public Result<Boolean> delete(@RequestParam String ids) {
        return Result.status(dictService.removeByIds(Arrays.asList(ids.split(","))));
    }
}

